#!/usr/bin/env bash
# Usage: goenv completions <command> [arg1 arg2...]
# Summary: Provides auto-completion for itself and other commands by calling them with `--complete`.

set -e
[ -n "$GOENV_DEBUG" ] && set -x

COMMAND="$1"
if [ -z "$COMMAND" ]; then
  goenv-help --usage completions >&2
  exit 1
fi

# Provide goenv completions
if [ "$COMMAND" = "--complete" ]; then
  exec goenv-commands
fi

COMMAND_PATH="$(command -v "goenv-$COMMAND" || command -v "goenv-sh-$COMMAND")"

# --help is provided automatically
echo --help

if grep -iE "^([#%]|--|//) provide goenv completions" "$COMMAND_PATH" >/dev/null; then
  shift
  exec "$COMMAND_PATH" --complete "$@"
fi
